package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.ProofGhanaMainProcessResult
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.ProofGhanaNextRouterResult
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import org.json.JSONArray
import org.json.JSONObject

class ProofGhanaWalletViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<ProofGhanaWalletResult>()
    val pageDetailResult: LiveData<ProofGhanaWalletResult> = _pageDetailResult

    private val _walletDeleteResult = MutableLiveData<ProofGhanaWalletDeleteResult>()
    val walletDeleteResult: LiveData<ProofGhanaWalletDeleteResult> = _walletDeleteResult

    private val _walletAddResult = MutableLiveData<ProofGhanaWalletAddResult>()
    val walletAddResult: LiveData<ProofGhanaWalletAddResult> = _walletAddResult

    private val _mainProcessResult = MutableLiveData<ProofGhanaMainProcessResult>()
    val mainProcessResult: LiveData<ProofGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult = MutableLiveData<ProofGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<ProofGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "wzutROeKRHbLUVhk4MDWJw"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONArray("obj") ?: JSONArray()
                var bindCount = 0
                val list = mutableListOf<JSONObject>()
                for (index in 0 until obj.length()) {
                    val item = obj[index] as JSONObject
                    item.put("isAdd", false)
                    list.add(item)
                }
                if (list.isEmpty()) {
                    list.add(JSONObject().apply {
                        put("isAdd", true)
                    })

                    list.add(JSONObject().apply {
                        put("isAdd", true)
                    })
                } else if (list.size == 1) {
                    bindCount = 1
                    list.add(JSONObject().apply {
                        put("isAdd", true)
                    })
                } else {
                    bindCount = list.size
                }

                _pageDetailResult.value = ProofGhanaWalletResult(
                    items = list,
                    bindCount = bindCount
                )
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                val obj = JSONArray()
                var bindCount = 0
                val list = mutableListOf<JSONObject>()
                for (index in 0 until obj.length()) {
                    val item = obj[index] as JSONObject
                    item.put("isAdd", false)
                    list.add(item)
                }
                if (list.isEmpty()) {
                    list.add(JSONObject().apply {
                        put("isAdd", true)
                    })

                    list.add(JSONObject().apply {
                        put("isAdd", true)
                    })
                } else if (list.size == 1) {
                    bindCount = 1
                    list.add(JSONObject().apply {
                        put("isAdd", true)
                    })
                } else {
                    bindCount = list.size
                }

                _pageDetailResult.value = ProofGhanaWalletResult(
                    items = list,
                    bindCount = bindCount,
                    error = errMsg
                )
            }
        })
    }

    /**
     * 删除钱包
     */
    fun askDeleteWallet(jsonObject: JSONObject) {
        val items = _pageDetailResult.value?.items ?: mutableListOf()
        _pageDetailResult.value = ProofGhanaWalletResult(
            items = items,
            showDelDialog = jsonObject,
            bindCount = curBindWalletCount()
        )
    }

    /**
     * 增加钱包
     */
    fun askAddWallet() {
        val items = _pageDetailResult.value?.items ?: mutableListOf()
        _pageDetailResult.value = ProofGhanaWalletResult(
            items = items,
            showAddDialog = true,
            bindCount = curBindWalletCount()
        )
    }

    /**
     * 增加钱包
     */
    fun confirmAddWallet(type: String, mobile: String) {
        if (type.isBlank() or mobile.isBlank()) {
            _walletAddResult.value = ProofGhanaWalletAddResult(error = "Wallet mobile is null")
            return
        }

        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "QN1wrGn9qlbu2fBPKFWhsw"
        action["walletMobile"] = mobile
        action["walletMobileConfirm"] = mobile
        action["walletChannel"] = type
        val isWave = type.contains("WAVE", true)
        val isFree = type.contains("FREE", true)
        action["addBindFlag"] = if (isWave or isFree) "YES" else "NO"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val addBindFlag = obj.optString("addBindFlag")
                val channel = obj.optString("channel")
                if (addBindFlag == "YES") {
                    var channelObj: JSONObject? = null
                    for (index in 0 until ProjectApplication.mWalletChannels.size) {
                        val item = ProjectApplication.mWalletChannels[index]
                        val itemValue = item.optString("value")
                        val itemLogo = item.optString("logo")
                        val itemDesc = item.optString("desc")
                        if (channel == itemValue) {
                            channelObj = JSONObject().apply {
                                put("value", itemValue)
                                put("logo", itemLogo)
                                put("desc", itemDesc)
                                put("mobile", mobile)
                            }
                            break
                        }
                    }
                    if (channelObj != null) {
                        _walletAddResult.value =
                            ProofGhanaWalletAddResult(success = obj, channel = channelObj)
                    } else {
                        _walletAddResult.value = ProofGhanaWalletAddResult(success = obj)
                    }
                } else {
                    _walletAddResult.value = ProofGhanaWalletAddResult(success = obj)
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _walletAddResult.value = ProofGhanaWalletAddResult(error = errMsg)
            }
        })
    }

    /**
     * 删除钱包
     */
    fun confirmDeleteWallet(walletId: String) {
        if (walletId.isNotBlank()) {
            _loadingResult.value = true
            val context = ProjectApplication.context
            val action = hashMapOf<String, Any>().createApiAction()
            action["path"] = "H9sdkh7TneOORr1n0UNMw"
            action["ids"] = walletId

            context.doPostRequest(action, object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    _loadingResult.value = false

                    pageDetail()
                }

                override fun onApiError(code: String, errMsg: String) {
                    _loadingResult.value = false

                    _walletDeleteResult.value = ProofGhanaWalletDeleteResult(error = errMsg)
                }
            })
        }
    }

    /**
     * 顺便绑其它渠道钱包
     */
    fun askBindChannelWallet() {
        val isBindChannel = _walletAddResult.value?.channel
        val items = _pageDetailResult.value?.items ?: mutableListOf()
        _pageDetailResult.value = ProofGhanaWalletResult(
            items = items,
            showBindChannelDialog = isBindChannel,
            bindCount = curBindWalletCount()
        )
    }

    /**
     * 保存钱包
     */
    fun submitWallets() {
        val items = _pageDetailResult.value?.items ?: mutableListOf()
        if (items.isEmpty()) {
            items.add(JSONObject().apply {
                put("isAdd", true)
            })

            items.add(JSONObject().apply {
                put("isAdd", true)
            })

            _pageDetailResult.value = ProofGhanaWalletResult(
                items = items,
                showEmptyDialog = true,
                bindCount = 0
            )
        } else {
            val idList = mutableListOf<String>()
            for (index in 0 until items.size) {
                val item = items[index]
                val id = item.optString("id")
                if (id.isNotBlank()) {
                    idList.add(id)
                }
            }
            if (idList.size >= 2) {
                mainProcess()
                _pageDetailResult.value = ProofGhanaWalletResult(
                    items = items,
                    showSubmitDialog = true,
                    bindCount = idList.size
                )
            } else {
                _pageDetailResult.value = ProofGhanaWalletResult(
                    items = items,
                    showEmptyDialog = true,
                    bindCount = idList.size
                )
            }
        }
    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = ProofGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value = ProofGhanaMainProcessResult(error = errMsg)
            }
        })
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromProof = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                ProofGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }

    /**
     * 获取当前有效绑卡数
     */
    private fun curBindWalletCount(): Int {
        val items = _pageDetailResult.value?.items ?: mutableListOf()
        val idList = mutableListOf<String>()
        for (index in 0 until items.size) {
            val item = items[index]
            val id = item.optString("id")
            if (id.isNotBlank()) {
                idList.add(id)
            }
        }
        return idList.size
    }
}